<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划编号" prop="planCode">
        <el-input
          v-model="queryParams.planCode"
          placeholder="请输入计划编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划状态" prop="approveStatus">
        <el-select v-model="queryParams.approveStatus" placeholder="计划状态" clearable>
          <el-option
            v-for="dict in dict.type.pur_plan_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:plan:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:plan:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchase:plan:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="planId" width="55"/>
      <el-table-column label="计划编号" align="center" prop="planCode"/>
      <el-table-column label="计划名称" align="center" prop="planName"/>
      <el-table-column label="计划状态" align="center" prop="approveStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pur_plan_status" :value="scope.row.approveStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="计划采购总额" align="center" prop="total"/>
      <el-table-column label="审批人" align="center" prop="approver"/>
      <el-table-column label="审批时间" align="center" prop="approveTime" width="160"/>
      <el-table-column label="审批意见" align="center" prop="approveOpinion" :show-overflow-tooltip="true" width="200"/>
      <el-table-column label="创建者" align="center" prop="createBy" width="120"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:plan:edit']"
            v-show="scope.row.approveStatus==0"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:plan:remove']"
            v-show="scope.row.approveStatus==0"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleView(scope.row)"
            v-show="scope.row.approveStatus!=0"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-top-right"
            @click="handleCommit(scope.row)"
            v-hasPermi="['purchase:plan:commit']"
            v-show="scope.row.approveStatus==0"
          >提交
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-bottom-left"
            @click="handleRecall(scope.row)"
            v-hasPermi="['purchase:plan:recall']"
            v-show="scope.row.approveStatus==1"
          >撤回
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-check"
            @click="handleApprove(scope.row)"
            v-hasPermi="['purchase:plan:approve']"
            v-show="scope.row.approveStatus==1"
          >审批
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-warning"
            @click="handleUnapprove(scope.row)"
            v-hasPermi="['purchase:plan:approve']"
            v-show="scope.row.approveStatus==2 || scope.row.approveStatus==3"
          >弃审
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划编码" prop="planCode">
              <el-input v-model="form.planCode" placeholder="计划编码自动生成" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入计划名称"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider content-position="center">采购计划子信息</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddLine"
          >增行
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleDeleteLine"
          >删行
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="form.planBodyList" :row-class-name="rowPlanBodyIndex"
                @selection-change="handlePlanBodySelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="序号" align="center" prop="index" width="50"/>
        <el-table-column label="采购部门" align="center" prop="deptId" width="160">
          <template slot-scope="scope">
            <el-select v-model="scope.row.deptId" placeholder="采购部门">
              <el-option
                v-for="dept in deptOption"
                :key="dept.deptId"
                :label="dept.deptName"
                :value="dept.deptId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="存货管理" align="center" prop="inventoryId" width="160">
          <template slot-scope="scope">
            <el-select v-model="scope.row.inventoryId" placeholder="存货管理">
              <el-option
                v-for="inventory in inventoryOption"
                :key="inventory.inventoryId"
                :label="inventory.inventoryName"
                :value="inventory.inventoryId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="计划采购数量" align="center" prop="planPurNumber" width="220">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.planPurNumber" :precision="2" :step="1" :min="0"/>
          </template>
        </el-table-column>
        <el-table-column label="计划采购单价" align="center" prop="planPrice" width="220">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.planPrice" :precision="2" :step="1" :min="0"/>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审批计划对话框 -->
    <el-dialog title="审批采购计划" :visible.sync="approveOpen" width="900px" append-to-body>
      <el-form ref="form" :model="approveForm" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="审批结果" prop="approveResult">
              <el-select v-model="approveForm.approveResult" placeholder="请选择审批结果">
                <el-option
                  v-for="approve in approveOption"
                  :key="approve.value"
                  :label="approve.label"
                  :value="approve.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审批意见" prop="approveOpinion">
              <el-input v-model="approveForm.approveOpinion" type="textarea" :rows="5" placeholder="请输入审批意见"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApproveForm">确 定</el-button>
        <el-button @click="cancelApprove">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看计划对话框 -->
    <el-dialog title="采购计划" :visible.sync="viewOpen" width="900px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划编码" prop="planCode">
              <el-input v-model="form.planCode" placeholder="计划编码自动生成" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="form.planName" placeholder="请输入计划名称" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider content-position="center">采购计划子信息</el-divider>
      <el-table :data="form.planBodyList" :row-class-name="rowPlanBodyIndex">
        <el-table-column label="序号" align="center" prop="index" width="100"/>
        <el-table-column label="采购部门" align="center" prop="deptId" width="160">
          <template slot-scope="scope">
            <span v-for="dept in deptOption">
              <span v-if="scope.row.deptId == dept.deptId">{{ dept.deptName }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="存货管理" align="center" prop="inventoryId" width="160">
          <template slot-scope="scope">
            <span v-for="inventory in inventoryOption">
              <span v-if="scope.row.inventoryId == inventory.inventoryId">{{ inventory.inventoryName }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="计划采购数量" align="center" prop="planPurNumber" width="220"/>
        <el-table-column label="计划采购单价" align="center" prop="planPrice" width="220"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeView">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPlan,
  approvePlan,
  commitPlan,
  delPlan,
  getPlan,
  listPlan,
  recallPlan, unapprovePlan,
  updatePlan
} from '@/api/purchase/plan'
import { listInventory } from '@/api/archive/inventory'
import { listDept } from '@/api/system/dept'

export default {
  name: 'Plan',
  dicts: ['pur_plan_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 计划表格数据
      planList: [],
      // 计划子表格选中数据
      checkedPlanBodyList: [],
      // 部门数据
      deptOption: [],
      // 存货数据
      inventoryOption: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planCode: undefined,
        planName: undefined,
        approveStatus: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planName: [
          { required: true, message: '计划名称不能为空', trigger: 'change' }
        ]
      },
      // 审批对话框显示开关
      approveOpen: false,
      // 审批表单
      approveForm: {},
      // 审批结果选项
      approveOption: [
        {
          label: '通过',
          value: 'pass'
        },
        {
          label: '不通过',
          value: 'notPass'
        },
        {
          label: '驳回',
          value: 'reject'
        }
      ],
      viewOpen: false
    }
  },
  created() {
    this.getList()
    this.getDeptList()
    this.getInventoryList()
  },
  methods: {
    getDeptList() {
      listDept().then(response => {
        this.deptOption = response.data
      })
    },
    getInventoryList() {
      listInventory().then(response => {
        this.inventoryOption = response.data
      })
    },
    /** 查询计划列表 */
    getList() {
      this.loading = true
      listPlan(this.queryParams).then(response => {
        this.planList = response.data
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        planId: undefined,
        planName: undefined,
        // 计划子表格数据
        planBodyList: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.planId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加计划'
      this.handleAddLine()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const planId = row.planId || this.ids
      getPlan(planId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改计划'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.planId != undefined) {
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids
      this.$modal.confirm('是否确认删除序号为"' + planIds + '"的数据项？').then(function() {
        return delPlan(planIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 增行按钮操作 */
    handleAddLine() {
      let obj = {}
      obj.deptId = ''
      obj.inventoryId = ''
      obj.planPurNumber = ''
      obj.planPrice = ''
      this.form.planBodyList.push(obj)
    },
    /** 删行按钮操作 */
    handleDeleteLine() {
      if (this.checkedPlanBodyList.length === 0) {
        this.$modal.msgError('请先选中需要删除的采购计划子信息')
      } else {
        const planBodyList = this.form.planBodyList
        const checkedPlanBodyList = this.checkedPlanBodyList
        this.form.planBodyList = planBodyList.filter(function(item) {
          return checkedPlanBodyList.indexOf(item.index) === -1
        })
      }
    },
    /** 采购计划子序号 */
    rowPlanBodyIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 采购计划子信息复选框选中数据 */
    handlePlanBodySelectionChange(selection) {
      this.checkedPlanBodyList = selection.map(item => item.index)
    },
    /** 提交采购计划 */
    handleCommit(row) {
      this.$modal.confirm('是否确认提交计划编号为"' + row.planCode + '"的数据项？').then(function() {
        return commitPlan(row)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('提交成功')
      }).catch(() => {
      })
    },
    /** 撤回采购计划 */
    handleRecall(row){
      this.$modal.confirm('是否确认撤回计划编号为"' + row.planCode + '"的数据项？').then(function() {
        return recallPlan(row)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('撤回成功')
      }).catch(() => {
      })
    },
    /** 审批采购计划 */
    handleApprove(row) {
      this.approveOpen = true
      this.approveForm = {
        planId: row.planId,
        approveResult: 'pass',
        approveOpinion: undefined
      }
    },
    /** 撤回采购计划 */
    handleUnapprove(row){
      this.$modal.confirm('是否确认弃审计划编号为"' + row.planCode + '"的数据项？').then(function() {
        return unapprovePlan(row)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('弃审成功')
      }).catch(() => {
      })
    },
    /** 确定审批 */
    submitApproveForm() {
      approvePlan(this.approveForm).then(res => {
        this.approveOpen = false
        this.getList()
        this.$modal.msgSuccess('审批成功')
      }).catch(() => {
      })
    },
    /** 取消审批 */
    cancelApprove() {
      this.approveOpen = false
      this.approveForm = {}
    },
    /** 查看 */
    handleView(row) {
      getPlan(row.planId).then(response => {
        this.form = response.data
        this.viewOpen = true
      })
    },
    /** 关闭查看 */
    closeView() {
      this.viewOpen = false
    }
  }
}
</script>
